import { getCinemaList } from '@/api/film'
import { getDistance } from '@/utils/util'

const getDefaultState = () => {
  return {
    cinemaList: [],
    areaList: [], // 区
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_LIST: (state, list) => {
    state.cinemaList = list || []
  },
  SET_AREA_LIST: (state, list) => {
    state.areaList = list
  }
}

const actions = {
  // 影院数据
  async getCinemaList({ commit, dispatch, rootGetters }) {
    const cityId = rootGetters['currentCity'].cityId
    const { data } = await getCinemaList({ cityId })

    commit('global/SET_DISCOUNT_RATE', data.selfDiscount, { root: true })
    return dispatch('sortCinemasByDistance', data.list)
  },

  // 获取区数据
  getAreaList({ commit }, cinemaList) {
    const areaList = []
    cinemaList.forEach(cinema => {
      if (!areaList.includes(cinema.regionName)) {
        areaList.push(cinema.regionName)
      }
    })
    commit('SET_AREA_LIST', areaList)
    return areaList
  },

  // 计算距离并排序
  sortCinemasByDistance({ commit, rootGetters }, cinemaList) {
    const currentLocation = rootGetters['currentLocation']
    if (currentLocation) {
      console.log('正在计算影院距离')
      cinemaList.forEach(cinema => {
        cinema.distance = getDistance(
          currentLocation.lat, 
          currentLocation.lng, 
          cinema.latitude, 
          cinema.longitude
        )
      })
      cinemaList.sort(({ distance: a }, { distance: b }) => a - b)
      console.log('影院距离计算成功', cinemaList)
    }
    commit('SET_LIST', cinemaList)
    return cinemaList
  },

  reset({ commit }) {
    return new Promise(resolve => {
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

